package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            //生成随即的4位数的短信验证码
            String string = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码："+string);
            //调用阿里云的短信服务，将验证码发给用户
            //SMSUtils.sendMessage("瑞吉外卖","",phone,string);

            //将生成的验证码存到session，方便之后与用户提交的验证码进行比对。
            session.setAttribute(phone,string);

            //用redis将生成的验证码保存在内存之中，使其读取效率更高，并设置5分钟之后消失。
          //  redisTemplate.opsForValue().set(phone,string,5, TimeUnit.MINUTES);
            return R.success("验证码获取成功");
        }
        return R.error("验证码获取失败");
    }

    /**
     *  因为前端传递过来的是一个对象里面有两个JSON的数据，所以可以用RequestBody封装成一个map对象
     *  因为map是一个集合，所以可以存放多个键值对
     * @param map
     */
    @PostMapping("/login")
    public R<User> loginApi(@RequestBody Map map, HttpSession session){
        String string = map.get("phone").toString();
        String string1 = map.get("code").toString();
        String string2 = session.getAttribute(string).toString();
        //用redis读取保留在内存中的验证码
       // String string2 = (String) redisTemplate.opsForValue().get(string);
        if(string2!=null&&string1.equalsIgnoreCase(string2)){
            final LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,string);
            User user = userService.getOne(userLambdaQueryWrapper);
            if(user==null){
                user = new User();
                user.setPhone(string);
                user.setStatus(1);
                user.setName(string);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            BaseContext.setCurrentId(user.getId());
            //验证码核对成功之后，应该将保留在内存中的验证码删除掉
          //  redisTemplate.delete(string);
          //  System.out.println("redisTemplate.opsForValue().get(string) = " + redisTemplate.opsForValue().get(string));
            return R.success(user);
        }
        return R.error("登录失败");
    }

    @PostMapping("/loginout")
    public R<String> loginoutApi(HttpServletRequest request){
               request.getSession().removeAttribute("user");
               return R.success("用户退出成功");
    }
}
